var userInfoManager_page={};

userInfoManager_page.action = {
    initBody:function () {
        userInfoManager_page.interface.initTablePage();
        userInfoManager_page.action.bindEvent();
    },
    bindEvent:function () {

        // userInfoManager_page.interface.initPlugins();
        $("#addBtn").click(function () {
            console.log("click");
            userInfoManager_page.interface.initPlugins();
            userInfoManager_page.interface.initFormPage();
            userInfoManager_page.action.bindEvent();
            return false;
        });
        $("#saveBtn").click(function () {
            console.log("saveBtn");
            userInfoManager_page.action.saveForm();
        });
        $("#cancelBtn").click(function () {
            //清空缓存的数据
            userInfoManager_page.data.userInfoData = {};
            userInfoManager_page.data.imgUpload = {};
            userInfoManager_page.data.provinceSelect = {};
            userInfoManager_page.data.citySelect = {};
            userInfoManager_page.data.areaSelect = {};
            userInfoManager_page.action.initBody();
        });
        //各种基于事件的操作，下面会有进一步介绍
        layui.use('form', function () {
            var form = layui.form;
            //三级联动
            form.on('select(province)', function (data) {
                console.log("province:"+data.value); //得到被选中的值
               userInfoManager_page.action.getAreaData(data.value,'city');
               userInfoManager_page.action.getAreaData(-1,'area');
            });

            form.on('select(city)', function (data) {
                console.log("city:"+data.value); //得到被选中的值
               userInfoManager_page.action.getAreaData(data.value,'area');
            });

            form.on('select(area)', function (data) {
                console.log("area:"+data.value); //得到被选中的值
            });

        });
    },
    saveForm:function () {
        console.log("save");
        var onSuccess = function (resultData) {
            layer.closeAll('loading');
            userInfoManager_page.data.imgUpload.clear();
            if (resultData.success) {
                layer.msg(resultData.error);
                userInfoManager_page.action.initBody();
            } else {
                layer.msg(resultData.error);
            }
        };

        layui.use('form', function(){
            console.log("use form");
            var form = layui.form;
            form.render();
            //监听提交
            form.on('submit(saveBtn1)', function(data){
                console.log("save form sub");
                data.field.fileJson = JSON.stringify(userInfoManager_page.data.imgUpload.getSingleUploadFile());
                console.log(data.field);
                layer.load();
                AppComm.ajax.execute({
                    'url':AppComm.url.getBaseURL()+'/userInfo/ajax/save',
                    'data':data.field,
                    'success':onSuccess
                });
                return false;
            });
        });


    },
    deleteUser:function (userId) {
        var params = {
            'userIds':userId
        };
        console.log(userId);
        var onSuccess = function (resultData) {
            if (resultData.success) {
                layer.msg("删除成功！");
                userInfoManager_page.data.tableIns.reload();
            }
        };
        AppComm.ajax.execute({
            'url':AppComm.url.getBaseURL()+'/userInfo/ajax/delete',
            'data':params,
            'success':onSuccess
        });
    },
    bindEventClose:function () {
        $(".close").click(function(){
            this.remove();
        })
    },
    getAreaData: function (pid,type) {
        var userData;
        if(userInfoManager_page.data.userInfoData != null){
            userData = userInfoManager_page.data.userInfoData.userInfo;
        }
        var data = {
            "pid":pid
        };
        var onSuccess = function (resultData) {
            if (resultData.success) {
                layui.use('form', function () {
                    var form = layui.form;
                    console.log("初始化:"+type);
                    var value = null;
                    if(resultData.data != null && resultData.data.length > 0){
                        value = resultData.data[0].value;
                    }
                    if (type == 'province') {
                        form.render('select', 'province');
                        var opt = {
                            "key":"省",
                            "value":""
                        };
                        resultData.data.unshift(opt);
                        userInfoManager_page.data.provinceSelect.allDataInit(null, resultData.data);
                        if(userData != null && userData.province != null){
                            $("#layerForm").find("dd[lay-value="+userData.province+"]").click();
                        }
                        //userInfoManager_page.action.getAreaData(value, "city");
                    }
                    if (type == 'city') {
                        var opt = {
                            "key":"市",
                            "value":""
                        };
                        resultData.data.unshift(opt);
                        form.render('select', 'city');
                        userInfoManager_page.data.citySelect.allDataInit(null, resultData.data);
                        if(userData != null && userData.city != null){
                            $("#layerForm").find("dd[lay-value="+userData.city+"]").click();
                        }
                    }
                    if (type == 'area') {
                        var opt = {
                            "key":"区",
                            "value":""
                        };
                        resultData.data.unshift(opt);
                        form.render('select', 'area');
                        userInfoManager_page.data.areaSelect.allDataInit(null, resultData.data);
                        if(userData != null && userData.area != null){
                            $("#layerForm").find("dd[lay-value="+userData.area+"]").click();
                        }
                    }

                });
            };
        }
        AppComm.ajax.execute({
            'url': AppComm.url.getBaseURL() + '/area/ajax/getAreaData',
            'data': data,
            'success': onSuccess
        });
    }
};

userInfoManager_page.interface = {
    // 加载表格页
    initTablePage:function () {
        var html = template("userInfoManagerList_template");
        $(".userManager_box").html(html);

        layui.use(['table','form'], function(){
            var table = layui.table;

            //执行表格渲染
            var tableIns = table.render({
                height:550,
                url:AppComm.url.getBaseURL()+'/userInfo/ajax/getList',
                elem:"#tb_list",
                page:true,
                limit:10,
                loading:true,
                id:'id',
                cols: [[
                    {
                        field:'fullname',
                        title:'姓名',
                        // width:200,
                        align:'left'
                    },
                    {
                        field:'username',
                        title:'账号',
                        //width:200,
                        align:'left'
                    },
                    {
                        field:'phone',
                        title:'电话号码',
                        //width:200,
                        align:'left'
                    },{
                        field:'email',
                        title:'邮箱',
                        //width:200,
                        align:'left'
                    },{
                        field:'orderId',
                        title:'排序号',
                        // width:200,
                        edit: 'text',
                        align:'left'
                    },
                    {
                        field:'comment',
                        title:'说明',
                        // width:200,
                        align:'left'
                    },
                    {
                        field:'opration',
                        title:'操作',
                        width:200,
                        fixed:'right',
                        align:'center',
                        toolbar:'#toolbar'
                    }
                ]]
            });

            userInfoManager_page.data.tableIns = tableIns;

            table.on('tool(tb_list)', function (obj) {
                //获取当前选中行
                var rowData = obj.data;
                var layEvent = obj.event;
                if (layEvent==='editBtn') {
                    console.log("编辑");
                    console.log(rowData.userId);
                    //点击编辑按钮需要进行的一些初始化操作
                    userInfoManager_page.interface.initPlugins();
                    userInfoManager_page.interface.initFormPage(rowData.userId);
                    userInfoManager_page.action.bindEvent();
                    // layer.alert(rowData.id+'ddsdfsdfsdfsdds',{icon: 3, title:'提示'});
                } else if (layEvent==='deleteBtn') {
                    layer.confirm('确定要进行删除吗？',{icon: 3, title:'提示'},function(index){
                        if(rowData.userId == "1"){
                            layer.alert("这是管理员，不要删除!");
                            return;
                        }
                        userInfoManager_page.action.deleteUser(rowData.userId);
                        layer.close(index);
                    }, function(index){
                        layer.close(index);
                    });
                }else if (layEvent === 'perBtn') {
                    userInfoManager_page.interface.initPermissionPage(rowData.userId);
                    userInfoManager_page.action.bindEvent();
                }
            });
            //修改排序字段
            table.on('edit(tb_list)', function(obj){
                var param ={
                    id:obj.data.userId,
                    orderId:obj.value,
                }
                var onSuccess = function (resultData) {
                    if (resultData.success) {
                        layer.msg("排序已修改！");
                        userInfoManager_page.action.initBody();
                    } else {
                        lay.msg("修改失败！");
                    }
                };
                AppComm.ajax.execute({
                    'url': AppComm.url.getBaseURL() + '/user/ajax/saveUser',
                    'data': param,
                    'success': onSuccess
                });
            });


            // 查询
            var form = layui.form;
            form.render(null, 'searchForm');
            form.on('submit(searchBtn)', function (data) {
                var postData = {
                    fullname: $.trim(data.field.username)
                };
                tableIns.reload({
                    where: postData
                });
                return false;
            });
        });

    },
    // 初始化表单页
    initFormPage:function (userId) {
        console.log("dataId:"+userId);
        if (userId==undefined || ''==userId.trim()) {
            // 添加
            var html = template("userInfoManagerForm_template");
            $(".userManager_box").html(html);
            layui.use('form', function(){
                var form = layui.form;
                form.render();
                //规则校验
                form.verify({
                    userNameValidate: function(value, item){ //value：表单的值、item：表单的DOM对象

                        if(!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)){
                            return '账号不能有特殊字符';
                        }
                        if(/(^\_)|(\__)|(\_+$)/.test(value)){
                            return '账号首尾不能出现下划线\'_\'';
                        }
                    }

                    ,passwdValidate: [
                        /^[\S]{6,12}$/
                        ,'密码必须6到12位，且不能出现空格'
                    ]
                });
            });
            //添加页面显示默认的图片
            $("#test_imgUpload2Preview").attr("src",AppComm.url.getBaseURL() +"/static/comm/img/defaultHead.jpg");
            return ;
        } else {
            // 编辑
            console.log("edit");
            layer.load();
            var params = {
                userId:userId
            };
            var onSuccess = function (resultData) {
                layer.closeAll('loading');
                userInfoManager_page.data.userInfoData = resultData.data;
                //获取上传头像的url
                var imgUrl = null;
                if(resultData.data.unitFile != null){
                    imgUrl = resultData.data.unitFile.sourceUrl;
                }
                var html = template("userInfoManagerForm_template", resultData.data);
                $(".userManager_box").html(html);
                //判断头像是否已经上传
                if(imgUrl == null || imgUrl == ""){
                    $("#test_imgUpload2Preview").attr("src",AppComm.url.getBaseURL()+"/static/comm/img/defaultHead.jpg");
                }
                //回显数据
                console.log("回显数据："+resultData.data.userInfo.sex);
                $("input:radio[value='"+resultData.data.userInfo.sex+"']").attr('checked','true');
                //账号密码不可修改
                $("#username").addClass("layui-disabled");
                $("#username").attr("disabled","true");
                //移除规则校验
                $("#username").removeAttr("lay-verify");
                $("#pswd").removeAttr("lay-verify");
                // $("#username").attr('disabled',"true");
                layui.use('form', function(){
                    var form = layui.form;
                    form.render();
                    //规则校验
                    form.verify({

                    });
                });
                userInfoManager_page.interface.initPlugins();
                userInfoManager_page.action.bindEvent();
            };
            AppComm.ajax.execute({
                'url':AppComm.url.getBaseURL()+'/userInfo/ajax/getUserInfo',
                'data':params,
                'success':onSuccess
            });
        }

    },
    // 初始化相关插件
    initPlugins: function(){
        //初始化图片上传插件
        var imgUpload = new CommonImageUpload("test_imgUpload2");
        userInfoManager_page.data.imgUpload = imgUpload;
        imgUpload.singleImageUploadInit(null);

        //初始化用户类型搜索框下拉
        var userTypeSelect =new CommonSelectedSearch("userTypeDiv","userType","/selectSeacrch/ajax/getSelectData");
        userTypeSelect.allDataInit({param:22});

        //初始化省市区搜索下拉框
        var provinceSelect = new CommonSelectedSearch("provinceDiv", "province", "/area/ajax/getAreaData");
        provinceSelect.allDataInit(null,[{
            "key":"省",
            "value":""
        }]);
        userInfoManager_page.data.provinceSelect = provinceSelect;

        var citySelect = new CommonSelectedSearch("cityDiv", "city", "/area/ajax/getAreaData");
        citySelect.allDataInit(null,[{
            "key":"市",
            "value":""
        }]);
        userInfoManager_page.data.citySelect = citySelect;
        //
        var areaSelect = new CommonSelectedSearch("araDiv", "area", "/area/ajax/getAreaData");
        areaSelect.allDataInit(null,[{
            "key":"区",
            "value":""
        }]);
        userInfoManager_page.data.areaSelect = areaSelect;

        userInfoManager_page.action.getAreaData(86,"province");
    },
    //角色授权界面初始化
    initPermissionPage: function (dataId) {
        var existParams={
            id:dataId
        }
        var html = template("userManagerList_role", {});
        var roleLayer = layer.open({
            type: 1,
            skin: 'layui-layer-rim', //加上边框
            area: '720px', //宽高
            content: html,
            offset: '100px'
        });
        var onSuccessExist = function (resultData) {
            console.log(resultData.data);
            if (resultData.success) {
                for(var i=0;i<resultData.data.length;i++){
                    var roLog = "<button class='close' style='margin:3px;display: inline-block;height: 38px;line-height: 38px;padding: 0 18px;border: 1px solid #C9C9C9;background-color: #fff;color: #555;white-space: nowrap;text-align: center;font-size: 14px;border-radius: 2px;cursor: pointer; -moz-user-select: none; -webkit-user-select: none;'"+"data_id="+resultData.data[i].id+">"+resultData.data[i].roleName+"<span class='layui-badge' >x</span></button>"
                    $("#roLog").append(roLog);
                    userInfoManager_page.action.bindEventClose();
                }
            }
        }
        AppComm.ajax.execute({
            'url':AppComm.url.getBaseURL()+'/role/ajax/getRolesByUserId',
            'data':existParams,
            'success':onSuccessExist
        });
        layui.use(['table', 'form'], function () {
            var table = layui.table;
            //执行表格渲染

            var roleTable = table.render({
                elem: "#ro_list",
                url: AppComm.url.getBaseURL()+'/role/ajax/getRoleManagerList',
                page: {
                    layout: ['count', 'prev', 'page', 'next', 'skip']
                },
                limit: 10,
                loading: true,
                id: 'ro_list',
                cols: [[
                    {
                        field: 'roleKey',
                        title: '角色关键字',
                        width: 200,
                        align: 'left',
                        event: 'setSign',
                    },
                    {
                        field: 'roleName',
                        title: '角色名称',
                        width: 200,
                        align: 'left',
                        event: 'setSign',
                    }, {
                        field: 'comment',
                        title: '角色说明',
                        width: 200,
                        align: 'left',
                        event: 'setSign',
                    }
                ]]
            });


            table.on('tool(ro_list)', function (obj) {
                var rowData = obj.data;
                var layEvent = obj.event;
                if(obj.event === 'setSign'){
                    var flag=0;
                    $("#roLog button").each(function(index,item) {
                        if($(item).attr("data_id")==rowData.id){
                            flag++
                        }
                    })
                    if(flag==0){
                        var roLog = "<button class='close' style='margin:3px;display: inline-block;height: 38px;line-height: 38px;padding: 0 18px;border: 1px solid #C9C9C9;background-color: #fff;color: #555;white-space: nowrap;text-align: center;font-size: 14px;border-radius: 2px;cursor: pointer; -moz-user-select: none; -webkit-user-select: none;'"+"data_id="+rowData.id+">"+rowData.roleName+"<span class='layui-badge' >x</span></button>"
                        $("#roLog").append(roLog);
                        userInfoManager_page.action.bindEventClose();
                    }
                    if(flag>0){
                        layer.msg('不能重复添加', {
                            time: 2000, //2s后自动关闭
                        });
                    }
                }
            });
            // 查询
            var form = layui.form;
            form.render(null, 'searchRoleForm');
            form.on('submit(searchRole)', function (data) {
                var postData = {
                    roleName: data.field.roleName
                };
                roleTable.reload({
                    where: postData
                });
                return false;
            });
            $("#getCheckData").click(function () {
                var roleD = new Array();
                $("#roLog button").each(function(index,item) {
                    roleD.push($(item).attr("data_id"));
                })
                var ids = roleD.join(",");
                var params= {
                    id:dataId,
                    ids:ids
                }
                var onSuccess1 = function (resultData) {
                    if (resultData.success) {
                        layer.close(roleLayer);
                        layer.msg("配置成功！");
                    }
                };
                AppComm.ajax.execute({
                    'url':AppComm.url.getBaseURL()+'/role/ajax/saveRolePer',
                    'data':params,
                    'success':onSuccess1
                });
                return false;
            });
        });

    }
};

userInfoManager_page.data = {
    "imgUpload" : {},
    "userInfoData":{},
    "provinceSelect":{},
    "citySelect":{},
    "areaSelect":{}
};

userInfoManager_page.event={
    'isReaded':false,
    onReady: function () {
        userInfoManager_page.action.initBody();
    }
};

AppComm.action.ready(function () {
    if (!userInfoManager_page.event.isReaded) {
        userInfoManager_page.event.isReaded = true;
        userInfoManager_page.event.onReady();
    }
});
